package cn.iocoder.yudao.hires.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.hires.entity.*;
import cn.iocoder.yudao.hires.mapper.*;
import cn.iocoder.yudao.hires.service.ResumeMainService;
import cn.iocoder.yudao.hires.service.notice.NoticeEnterpriseService;
import cn.iocoder.yudao.hires.vo.ResumeMainPageReqVO;
import cn.iocoder.yudao.hires.vo.ResumeMainSaveReqVO;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;

@Service
@Validated
public class ResumeMainServiceImpl implements ResumeMainService {

    @Resource
    private ResumeMainMapper mainMapper;
    @Resource
    private ResumeUserMapper userMapper;

    @Resource
    private ResumeIntentionMapper intentionMapper;

    @Resource
    private ResumeEducationMapper educationMapper;

    @Resource
    private ResumeWorkMapper workMapper;

    @Resource
    private ResumeProjectMapper projectMapper;

    @Resource
    private ResumeTrainingMapper trainingMapper;

    @Resource
    private ResumeSkillMapper skillMapper;

    @Resource
    private ResumeEvaluationMapper evaluationMapper;
    @Resource
    private ResumeOpusMapper opusMapper;
    @Resource
    private ResumeTagsMapper tagsMapper;

    @Resource
    private NoticeEnterpriseService noticeEnterpriseService;

    @Override
    public Integer createMain(ResumeMainSaveReqVO createReqVO) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        //用户基本资料
        ResumeUserDO resumeUserDO = createReqVO.getResumeUserDO();
        if (resumeUserDO != null) {
            resumeUserDO.setUserId(Math.toIntExact(userId));
            userMapper.insert(resumeUserDO);
        }

        //求职意向
        List<ResumeIntentionDO> resumeIntentionDOS = createReqVO.getResumeIntentionDO();
        if (resumeIntentionDOS != null) {
            for (ResumeIntentionDO resumeIntentionDO : resumeIntentionDOS) {
                resumeIntentionDO.setUserId(Math.toIntExact(userId));
                intentionMapper.insert(resumeIntentionDO);
            }
        }
        //教育经历
        List<ResumeEducationDO> resumeEducationDOS = createReqVO.getResumeEducationDOS();
        if (resumeEducationDOS != null) {
            for (ResumeEducationDO resumeEducationDO : resumeEducationDOS) {
                resumeEducationDO.setUserId(Math.toIntExact(userId));
                educationMapper.insert(resumeEducationDO);

            }
        }

        //工作经历
        List<ResumeWorkDO> resumeWorkDOS = createReqVO.getResumeWorkDOS();
        if (resumeWorkDOS != null) {
            for (ResumeWorkDO resumeWorkDO : resumeWorkDOS) {
                resumeWorkDO.setUserId(Math.toIntExact(userId));
                workMapper.insert(resumeWorkDO);
            }
        }

        //项目经历
        List<ResumeProjectDO> resumeProjectDOS = createReqVO.getResumeProjectDOS();
        if (resumeProjectDOS != null) {
            for (ResumeProjectDO resumeProjectDO : resumeProjectDOS) {
                resumeProjectDO.setUserId(Math.toIntExact(userId));
                projectMapper.insert(resumeProjectDO);
            }
        }
        //培训经历
        List<ResumeTrainingDO> resumeTrainingDOS = createReqVO.getResumeTrainingDOS();
        if (resumeTrainingDOS != null) {
            for (ResumeTrainingDO resumeTrainingDO : resumeTrainingDOS) {
                resumeTrainingDO.setUserId(Math.toIntExact(userId));
                trainingMapper.insert(resumeTrainingDO);
            }
        }
        //职业技能
        List<ResumeSkillDO> resumeSkillDOS = createReqVO.getResumeSkillDOS();
        if (resumeSkillDOS != null) {
            for (ResumeSkillDO resumeSkillDO : resumeSkillDOS) {
                resumeSkillDO.setUserId(Math.toIntExact(userId));
                skillMapper.insert(resumeSkillDO);
            }
        }
        //个人评价
        ResumeEvaluationDO resumeEvaluationDO = createReqVO.getResumeEvaluationDO();
        if (resumeEvaluationDO != null) {
            resumeEvaluationDO.setUserId(Math.toIntExact(userId));
            evaluationMapper.insert(resumeEvaluationDO);
        }

        List<ResumeOpusDO> opus = createReqVO.getOpus();
        if (opus != null) {
            for (ResumeOpusDO resumeOpusDO : opus) {
                resumeOpusDO.setUserId(Math.toIntExact(userId));
                opusMapper.insert(resumeOpusDO);
            }
        }
        ResumeTagsDO resumeTagsDO = createReqVO.getResumeTagsDO();
        if (resumeTagsDO != null) {
            resumeTagsDO.setUserId(Math.toIntExact(userId));
            tagsMapper.insert(resumeTagsDO);
        }
        // 插入
        ResumeMainDO main = BeanUtils.toBean(createReqVO, ResumeMainDO.class);
        mainMapper.insert(main);
        // 返回
        return main.getId();

    }

    @Override
    public void updateMain(ResumeMainSaveReqVO updateReqVO) {
        // 校验存在
        Integer id = updateReqVO.getId();
        validateMainExists(updateReqVO.getId());
        // 更新
        ResumeMainDO updateObj = BeanUtils.toBean(updateReqVO, ResumeMainDO.class);
        Long userId = SecurityFrameworkUtils.getLoginUserId();

        //用户基本资料
        ResumeUserDO resumeUserDO = updateReqVO.getResumeUserDO();
        if (resumeUserDO != null) {
            //用户基本资料
            userMapper.delete(ResumeUserDO::getUserId, userId);
            userMapper.insert(resumeUserDO);
        }

        //求职意向
        List<ResumeIntentionDO> resumeIntentionDOs = updateReqVO.getResumeIntentionDO();

        if (resumeIntentionDOs != null) {
            intentionMapper.delete(ResumeIntentionDO::getUserId, userId);
            for (ResumeIntentionDO resumeIntentionDO : resumeIntentionDOs) {
                intentionMapper.insert(resumeIntentionDO);
            }
        }

        //教育经历
        List<ResumeEducationDO> resumeEducationDOS = updateReqVO.getResumeEducationDOS();
        if (resumeEducationDOS != null) {
            educationMapper.delete(ResumeEducationDO::getUserId, userId);
            for (ResumeEducationDO resumeEducationDO : resumeEducationDOS) {
                //教育经历
                educationMapper.insert(resumeEducationDO);
            }
        }

        //工作经历
        List<ResumeWorkDO> resumeWorkDOS = updateReqVO.getResumeWorkDOS();
        if (resumeWorkDOS != null) {
            workMapper.delete(ResumeWorkDO::getUserId, userId);
            for (ResumeWorkDO resumeWorkDO : resumeWorkDOS) {
                //工作经历
                workMapper.insert(resumeWorkDO);
            }
        }

        //项目经历
        List<ResumeProjectDO> resumeProjectDOS = updateReqVO.getResumeProjectDOS();
        if (resumeProjectDOS != null) {
            projectMapper.delete(ResumeProjectDO::getUserId, userId);
            for (ResumeProjectDO resumeProjectDO : resumeProjectDOS) {
                //项目经历
                projectMapper.insert(resumeProjectDO);
            }
        }
        //培训经历
        List<ResumeTrainingDO> resumeTrainingDOS = updateReqVO.getResumeTrainingDOS();
        if (resumeTrainingDOS != null) {
            for (ResumeTrainingDO resumeTrainingDO : resumeTrainingDOS) {
                //培训经历
                trainingMapper.delete(ResumeTrainingDO::getUserId, userId);
                trainingMapper.insert(resumeTrainingDO);
            }
        }
        //职业技能
        List<ResumeSkillDO> resumeSkillDOS = updateReqVO.getResumeSkillDOS();
        if (resumeSkillDOS != null) {
            skillMapper.delete(ResumeSkillDO::getUserId, userId);
            for (ResumeSkillDO resumeSkillDO : resumeSkillDOS) {
                //职业技能
                skillMapper.insert(resumeSkillDO);
            }
        }
        //个人评价
        ResumeEvaluationDO resumeEvaluationDO = updateReqVO.getResumeEvaluationDO();
        if (resumeEvaluationDO != null) {
            //个人评价
            evaluationMapper.delete(ResumeEvaluationDO::getUserId, userId);
            evaluationMapper.insert(resumeEvaluationDO);
        }
        List<ResumeOpusDO> opus = updateReqVO.getOpus();
        if (opus != null) {
            for (ResumeOpusDO resumeOpusDO : opus) {
                opusMapper.delete(ResumeOpusDO::getUserId, userId);
                opusMapper.insert(resumeOpusDO);
            }
        }
        ResumeTagsDO resumeTagsDO = updateReqVO.getResumeTagsDO();
        if (resumeTagsDO != null) {
            tagsMapper.delete(ResumeTagsDO::getUserId, userId);
            tagsMapper.insert(resumeTagsDO);
        }
        mainMapper.updateById(updateObj);
    }

    private void validateMainExists(Integer id) {
        if (mainMapper.selectById(id) == null) {
            throw exception(new ErrorCode(500, "简历-主体不存在"));
        }
    }


    @Override
    public void deleteMain(Integer userId) {

        // 删除
        mainMapper.delete(ResumeMainDO::getUserId, userId);
        //用户基本资料
        userMapper.delete(ResumeUserDO::getUserId, userId);
        //求职意向
        intentionMapper.delete(ResumeIntentionDO::getUserId, userId);
        //教育经历
        educationMapper.delete(ResumeEducationDO::getUserId, userId);
        //工作经历
        workMapper.delete(ResumeWorkDO::getUserId, userId);
        //项目经历
        projectMapper.delete(ResumeProjectDO::getUserId, userId);
        //培训经历
        trainingMapper.delete(ResumeTrainingDO::getUserId, userId);
        //职业技能
        skillMapper.delete(ResumeSkillDO::getUserId, userId);
        //个人评价
        evaluationMapper.delete(ResumeEvaluationDO::getUserId, userId);
    }

    @Override
    public ResumeMainDO getMain(Integer id) {
        return mainMapper.selectById(id);
    }

    @Override
    public PageResult<ResumeMainDO> getMainPage(ResumeMainPageReqVO pageReqVO) {
        return mainMapper.selectPage(pageReqVO);
    }

    @Override
    public Map<String, Object> getDetail(Integer userId, String intentionPost, Integer tenantId) {
        Map<String, Object> resume = new HashMap<>();
        //用户基本资料
        ResumeUserDO resumeUserDO = this.userMapper.selectOne(ResumeUserDO::getUserId, userId, ResumeUserDO::getDeleted, 0);
        if (BeanUtil.isEmpty(resumeUserDO)) {
            return new HashMap<>();
        }
        //求职意向
        LambdaQueryWrapperX<ResumeIntentionDO> eq = new LambdaQueryWrapperX<ResumeIntentionDO>().eq(ResumeIntentionDO::getUserId, userId).eq(ResumeIntentionDO::getDeleted, 0);
        if (StringUtils.isNotEmpty(intentionPost)) {
            eq.eq(ResumeIntentionDO::getIntentionPost, intentionPost);
        }
        List<ResumeIntentionDO> resumeIntentionDO = intentionMapper.selectList(eq);
        //教育经历
        List<ResumeEducationDO> resumeEducationDOS = educationMapper.selectList(ResumeEducationDO::getUserId, userId, ResumeEducationDO::getDeleted, 0);
        //工作经历
        List<ResumeWorkDO> resumeWorkDOS = workMapper.selectList(ResumeWorkDO::getUserId, userId, ResumeWorkDO::getDeleted, 0);
        //项目经历
        List<ResumeProjectDO> resumeProjectDOS = projectMapper.selectList(ResumeProjectDO::getUserId, userId, ResumeProjectDO::getDeleted, 0);
        //培训经历
        List<ResumeTrainingDO> resumeTrainingDOS = trainingMapper.selectList(ResumeTrainingDO::getUserId, userId, ResumeTrainingDO::getDeleted, 0);
        //职业技能
        List<ResumeSkillDO> resumeSkillDOS = skillMapper.selectList(ResumeSkillDO::getUserId, userId, ResumeSkillDO::getDeleted, 0);
        //个人评价
        ResumeEvaluationDO resumeEvaluationDO = evaluationMapper.selectOne(ResumeEvaluationDO::getUserId, userId, ResumeEvaluationDO::getDeleted, 0);
        List<ResumeOpusDO> opus = opusMapper.selectList(ResumeOpusDO::getUserId, userId, ResumeOpusDO::getDeleted, 0);
        ResumeTagsDO resumeTagsDO = tagsMapper.selectOne(ResumeTagsDO::getUserId, userId, ResumeTagsDO::getDeleted, 0);
        resume.put("user", resumeUserDO == null ? new ResumeUserDO() : resumeUserDO);
        resume.put("intention", resumeIntentionDO);
        resume.put("education", CollectionUtils.isEmpty(resumeEducationDOS) ? new ArrayList<>() : resumeEducationDOS);
        resume.put("work", CollectionUtils.isEmpty(resumeWorkDOS) ? new ArrayList<>() : resumeWorkDOS);
        resume.put("project", CollectionUtils.isEmpty(resumeProjectDOS) ? new ArrayList<>() : resumeProjectDOS);
        resume.put("training", CollectionUtils.isEmpty(resumeTrainingDOS) ? new ArrayList<>() : resumeTrainingDOS);
        resume.put("skill", CollectionUtils.isEmpty(resumeSkillDOS) ? new ArrayList<>() : resumeSkillDOS);
        resume.put("evaluation", resumeEvaluationDO == null ? new ResumeEducationDO() : resumeEvaluationDO);
        resume.put("opus", opus == null ? new ArrayList<>() : opus);
        resume.put("tags", resumeTagsDO == null ? new ResumeTagsDO() : resumeTagsDO);
        if(ObjectUtil.isNotEmpty(tenantId)){
            //  是否已经存在人才库
            if(CollUtil.isNotEmpty(resumeIntentionDO)){
                String collect = resumeIntentionDO.stream()
                        .map(ResumeIntentionDO::getIntentionPost)
                        .filter(post -> post != null && !post.trim().isEmpty()) // 过滤空值
                        .collect(Collectors.joining(", "));
                boolean flag = noticeEnterpriseService.getNoticeEnterpriseListEnterpr(userId, collect, tenantId);
                resume.put("isPool", flag);
            }else {
                resume.put("isPool", false);
            }
        }
        return resume;
    }

    /**
     * 根据职位id  获取简历数据
     *
     * @param categoryId 职位字典id
     * @return 简历数据
     */
    @Override
    public List<Map<String, Object>> resumeLibrary(Integer categoryId) {
        return mainMapper.resumeLibrary(categoryId);
    }

}
